package com.wwwarehouse.common.fragment;

import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wwwarehouse.common.R;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.adapter.carddesk.MyFragmentPagerAdapter;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.SlideBarView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.http.NetUtils;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * Common Pager Fragment
 * Created by ShineF on 2017/10/18 0018.
 */

public abstract class CommonBasePagerFragment extends BaseFragment implements ElasticScrollView.OnPullListener {

    protected ElasticScrollView mElasticView;
    protected CustomViewPagerInternal mCustomPager;
    protected CirclePageIndicator mPagerIndicator;
    private SlideBarView mSlideBar;
    protected StateLayout mStateLayout;
    protected LinearLayout mCardItem;
    protected Button mConfirmBtn;
    private RelativeLayout mRlParent;
    private boolean isShowCustomBtn = false;
    protected List<Fragment> mFragmentList;
    private int mCustomBtnNum = -1;
    private boolean mIsCardFragment = true;
    protected ImageView mEmptyImg;
    protected TextView mEmptyText;
    protected String mSearchText = null;
    protected LinearLayout mRlEmptyLayout;
    private RelativeLayout mRlConfirm;
    private boolean isVisibility = false;
    protected boolean isFirst = true;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_common_pager, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mElasticView = $(R.id.ecl_custom);
        mCustomPager = $(R.id.vp_content);
        mPagerIndicator = $(R.id.pager_indicator);
        mStateLayout = $(R.id.sl_state);
        mCardItem = $(R.id.rl_bkg);
        mConfirmBtn = $(R.id.confirm_btn);
        mRlParent = $(R.id.rl_parent);
        mEmptyImg = $(R.id.iv_empty);
        mEmptyText = $(R.id.tv_empty);
        mRlEmptyLayout = $(R.id.ll_empty);
        mSlideBar = $(R.id.sbv_slide);
        mRlConfirm = $(R.id.rl_confirm);
        mStateLayout.showProgressView("正在加载...", mIsCardFragment);
    }


    @Override
    public void setTitle() {

    }

    public void showConfirmButton() {
        mRlConfirm.setVisibility(View.VISIBLE);
        isVisibility = true;
    }

    public void hideConfirmButton() {
        mRlConfirm.setVisibility(View.GONE);
        isVisibility = false;
    }

    public RelativeLayout getConfirmLayout() {
        return mRlConfirm;
    }

    /**
     * 默认是卡片Fragment 如果不是卡片Fragment在requestData() super之前调用该方法,
     *
     * @param isCardFragment 是否是卡片fragment
     */
    public void isCardFragment(boolean isCardFragment) {
        this.mIsCardFragment = isCardFragment;
    }

    public void showCustomBtn(String... str) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mCustomBtnNum = str.length;
            for (int i = 0; i < str.length; i++) {
                try {
                    Method method = BaseCardDeskActivity.class.getMethod("setTitleBt" + (i + 1) + "Text", String.class);
                    Object[] objects = new String[]{str[i]};
                    method.invoke(mActivity, objects);
                } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            isShowCustomBtn = true;
        }
    }

    public ViewGroup getParentLayout() {
        return mRlParent;
    }

    public View getConfirmBtn() {
        return mConfirmBtn;
    }


    public void setConfirmBtnText(String text) {
        mConfirmBtn.setText(text);
    }

    @Override
    public void requestDatas() {
        mFragmentList = new ArrayList<>();
        mElasticView.setOnPullListener(this);
        mStateLayout.setSystemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mStateLayout.showProgressView("正在加载...", mIsCardFragment);
                onRefreshListener();
            }
        });
        mStateLayout.setNetworkListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mStateLayout.showProgressView("正在加载...", mIsCardFragment);
                onRefreshListener();
            }
        });
        mStateLayout.setEmptyListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mStateLayout.showProgressView("正在加载...", mIsCardFragment);
                onRefreshListener();
            }
        });
    }

//    @Override
//    public void onDownPull() {
//        if (!isShow) {
//            if (isShowCustomBtn) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                    for (int i = 0; i < mCustomBtnNum; i++) {
//                        try {
//                            Class<?>[] types = new Class[0];
//                            Method method = BaseCardDeskActivity.class.getMethod("showTitleBt" + (i + 1), types);
//                            method.invoke(mActivity);
//                        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            } else {
//                ((BaseCardDeskActivity) mActivity).showSearchTitle();
//            }
//        } else {
//            if (isShowCustomBtn) {
//                ((BaseCardDeskActivity) mActivity).hideTitleBt();
//            } else {
//                ((BaseCardDeskActivity) mActivity).hideSearchTitle();
//                ((BaseCardDeskActivity) mActivity).hideSearchInput();
//            }
//        }
//        isShow = !isShow;
//    }

    @Override
    public void onDownPull() {
        if (isShowCustomBtn) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                try {
                    Class<?>[] types = new Class[0];
                    Method method = BaseCardDeskActivity.class.getMethod("showTitleBt" + mCustomBtnNum, types);
                    method.invoke(mActivity);
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            ((BaseCardDeskActivity) (mActivity)).downPull_3();
        } else {
            ((BaseCardDeskActivity) (mActivity)).downPull_4();
        }
    }

    @Override
    public void onUpPull() {

    }

    /**
     * 数据请求
     *
     * @param url  请求链接
     * @param map  请求参数
     * @param what 请求what
     */
    public void loadData(String url, Map<String, Object> map, int what) {
        if (NetUtils.isHttpConnected(mActivity)) {
            NoHttpUtils.httpPost(url, map, new NoHttpUtils.OnResponseListener() {
                @Override
                public void onSucceed(CommonClass commonClass, int i) {
                    if ("0".equals(commonClass.getCode())) {
                        if (commonClass.getData() == null && isFirst) {
                            mStateLayout.showEmptyView(true);
                        } else if (commonClass.getData() == null && !isFirst) {
                            onLoadSuccess("", i);
                        } else {
                            onLoadSuccess(commonClass.getData().toString(), i);
                        }
                    } else if (!isFirst) {
                        if (TextUtils.isEmpty(commonClass.getMsg())) {
                            return;
                        }
                        ToastUtils.showToast(commonClass.getMsg());
                    } else {
                        mStateLayout.showSystemView(commonClass.getMsg(), true);
                    }
                }

                @Override
                public void onFailed(String s, int i) {
                    onLoadError(s);
                }

                @Override
                public void onFinish(int i) {

                }
            }, what);
        } else {
            mStateLayout.showNetworkView(mIsCardFragment);
        }

    }


    /**
     * 设置数据
     *
     * @param total         总页数
     * @param size          每一页显示几个
     * @param mFragmentName fragment全类名
     * @param bundle        参数
     * @param dataList      数据集合
     */
    public void setData(int total, int size, String mFragmentName, Bundle bundle, ArrayList<? extends Parcelable> dataList) throws Exception {
        mFragmentList.clear();
        int pager;
        if (size == 0) {
            throw new Exception("size不能为0");
        }
        if (total % size == 0) {
            pager = total / size;
        } else {
            pager = (total / size) + 1;
        }
        for (int i = 0; i < pager; i++) {
            Fragment fragment = Fragment.instantiate(mActivity, mFragmentName);
            Bundle pagerBundle = new Bundle();
            if (bundle != null) {
                pagerBundle.putAll(bundle);
            }
            pagerBundle.putInt("page", i + 1);
            pagerBundle.putParcelableArrayList("dataList", dataList);
            fragment.setArguments(pagerBundle);
            mFragmentList.add(fragment);
        }
        if (isAdded()) {
            MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getChildFragmentManager(), mFragmentList);
            mCustomPager.setAdapter(pagerAdapter);
            mCustomPager.setOffscreenPageLimit(3);
            if (pager <= 1) {
                mPagerIndicator.setVisibility(View.GONE);
                mSlideBar.setVisibility(View.GONE);
            } else if (pager > 1 && pager <= 6) {
                mPagerIndicator.setVisibility(View.VISIBLE);
                mSlideBar.setVisibility(View.GONE);
                if (mFragmentList.size() > 0) {
                    mPagerIndicator.setViewPager(mCustomPager, 0);
                }
                mPagerIndicator.notifyDataSetChanged();
            } else if (pager > 1 && pager > 6) {
                mPagerIndicator.setVisibility(View.GONE);
                mSlideBar.setVisibility(View.VISIBLE);
                mSlideBar.setTotalPage(pager);
                mSlideBar.setOnSlideChange(new SlideBarView.OnSlideChange() {
                    @Override
                    public void onSlideChange(int page) {
                        mCustomPager.setCurrentItem(page, false);
                    }
                });
                mSlideBar.setViewPagerInternal(mCustomPager);
            }
            mCardItem.setVisibility(View.VISIBLE);
        }
        if (dataList == null) {
            mRlConfirm.setVisibility(View.GONE);
            mRlEmptyLayout.setVisibility(View.GONE);
            mStateLayout.showEmptyView(getString(R.string.common_base_pager_no_data), mIsCardFragment);
        } else if (dataList.size() == 0 && !TextUtils.isEmpty(mSearchText)) {
            mRlConfirm.setVisibility(View.GONE);
            mRlEmptyLayout.setVisibility(View.VISIBLE);
            mEmptyImg.setImageResource(R.drawable.search_empty);
            mEmptyText.setText(R.string.invite_search_no_result);
            mStateLayout.showContentView();
            mCardItem.setVisibility(View.GONE);
        } else if (dataList.size() == 0 && TextUtils.isEmpty(mSearchText)) {
            mRlConfirm.setVisibility(View.GONE);
            mRlEmptyLayout.setVisibility(View.GONE);
            mStateLayout.showEmptyView(getString(R.string.common_base_pager_no_data), mIsCardFragment);
        }
        if (dataList != null && dataList.size() > 0) {
            if (isVisibility) {
                mRlConfirm.setVisibility(View.VISIBLE);
            }
            if (mCardItem.getVisibility() == View.GONE) {
                mCardItem.setVisibility(View.VISIBLE);
            }
            mRlEmptyLayout.setVisibility(View.GONE);
            mStateLayout.showContentView();
            dismissProgressDialog();
        }
    }

    /**
     * 显示空页面
     *
     * @param drawableId 图片
     * @param textId     文字
     */
    public void showEmptyView(int drawableId, int textId, boolean isShowConfirmBtn, boolean isShowCardBkg) {
        if (isShowConfirmBtn) {
            mRlConfirm.setVisibility(View.VISIBLE);
        } else {
            mRlConfirm.setVisibility(View.GONE);
        }
        if (isShowCardBkg) {
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            lp.setMargins(ConvertUtils.dip2px(mActivity, 11), ConvertUtils.dip2px(mActivity, 5)
                    , ConvertUtils.dip2px(mActivity, 11), ConvertUtils.dip2px(mActivity, 38));
            mRlEmptyLayout.setLayoutParams(lp);
            mRlEmptyLayout.setBackground(ContextCompat.getDrawable(mActivity, R.drawable.common_card_background_fff_shape));
        } else {
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            lp.setMargins(0, 0, 0, 0);
            mRlEmptyLayout.setLayoutParams(lp);
            mRlEmptyLayout.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.common_color_c10_eceff3));
        }
        mCardItem.setVisibility(View.GONE);
        mRlEmptyLayout.setVisibility(View.VISIBLE);
        mStateLayout.showContentView();
        mEmptyImg.setImageResource(drawableId);
        mEmptyText.setText(textId);
    }

    /**
     * stateLayout刷新方法
     */

    public abstract void onRefreshListener();

    /**
     * 网络加载成功回调
     *
     * @param data 成功数据
     * @param what 请求what
     */
    public abstract void onLoadSuccess(String data, int what);

    /**
     * 网络加载失败回调
     *
     * @param errorInfo 失败信息
     */
    public abstract void onLoadError(String errorInfo);

    @Override
    public void searchOnRealTimeClick(String text) {
        String content = text;
        String searchRuleName;
        if (TextUtils.isEmpty(content)) {
            searchRuleName = "";
        } else {
            searchRuleName = content;
        }
        textChanged(searchRuleName);
    }

    @Override
    public void searchNoRealTimeClick(String text) {
        super.searchNoRealTimeClick(text);
        String content = text;
        String searchRuleName;
        if (TextUtils.isEmpty(content)) {
            searchRuleName = "";
        } else {
            searchRuleName = content;
        }
        textNoRealChanged(searchRuleName);
    }

    public void textNoRealChanged(String text) {
        this.mSearchText = text;
    }

    /**
     * 搜索文字改变监听
     *
     * @param text 搜索文字
     */
    public void textChanged(String text) {
        this.mSearchText = text;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isFirst = true;
    }
}
